package com.tiemei.demo.json;

import static com.tiemei.demo.util.Print.p;

import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;


/**
 * http://www.mkyong.com/java/json-simple-example-read-and-write-json/
 * http://code.google.com/p/json-simple/
 *
 * @author tiemei.jdk
 * @date   2012-11-7
 */
public class JSONSimple {
	public static void main(String args[]) throws ParseException{
		// run
		String jsonString = toJSONString(); // Object to JSONString
		p(jsonString);
		JSONObject jsonObject = fromJSONString(jsonString); // JSONString to Object
		
		
		// output look
		String name = (String) jsonObject.get("name");
		p(name);
 
		long age = (Long) jsonObject.get("age");
		p(age);
 
		// loop array
		JSONArray msg = (JSONArray) jsonObject.get("messages");
		Iterator<String> iterator = msg.iterator();
		while (iterator.hasNext()) {
			p(iterator.next());
		}
		
		jsonObject = fromJSONString("{\"auction\":[{\"feedbackNick\":\"\",\"feedbackContent\":\"\",\"promoPrice\":\"\",\"auction_id\":\"1500002607104\",\"promoOtherNeed\":\"\",\"timeDiscountPrice\":\"\",\"promoName\":\"\",\"feedbackCount\":\"\",\"timeDiscountRate\":\"\"},{\"feedbackNick\":\"\",\"feedbackContent\":\"\",\"promoPrice\":\"\",\"auction_id\":\"1500017004124\",\"promoOtherNeed\":\"\",\"timeDiscountPrice\":\"\",\"promoName\":\"\",\"feedbackCount\":\"\",\"timeDiscountRate\":\"\"}],\"user\":[{\"dsrDescribe\":\"\",\"dsrServiceGap\":\"\",\"dsrService\":\"\",\"dsrDescribeGap\":\"\",\"user_id\":\"888$\",\"dsrInd\":\"\",\"dsrDeliver\":\"\",\"dsrDeliverGap\":\"\"}]}");
		JSONArray auctions = (JSONArray)jsonObject.get("auction");
		iterator = auctions.iterator();
		while (iterator.hasNext()) {
//			p(iterator.next().get("auction_id"));
		}
	}
	
	private static String toJSONString() {
		JSONObject obj = new JSONObject();
		obj.put("name", "mkyong.com");
		obj.put("age", new Integer(100));
	 
		JSONArray list = new JSONArray();
		list.add("msg 1");
		list.add("msg 2");
		list.add("msg 3");
	 
		obj.put("messages", list);
		
		return obj.toJSONString();
	} 
	
	private static JSONObject fromJSONString(String jsonString) throws ParseException {
		JSONParser parser = new JSONParser();
		Object obj = parser.parse(jsonString); // 支持 in / str
		JSONObject jsonObject = (JSONObject) obj;
		
		return jsonObject;
	}
}
